package com.zrrd.gmall.list.service.impl;


import com.alibaba.fastjson.JSON;
import com.zrrd.gmall.list.service.GoodsRepository;
import com.zrrd.gmall.list.service.SearchService;
import com.zrrd.gmall.model.list.*;
import com.zrrd.gmall.model.product.*;
import com.zrrd.gmall.product.fegin.ProductFeignClient;

import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ProductFeignClient productFeignClient;
    //操作es
    @Autowired
    private GoodsRepository goodsRepository;
    //用来存热度
    @Autowired
    private RedisTemplate redisTemplate;
    //搜索请求的对象
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public void upperGoods(Long skuId) {
        Goods goods = new Goods();
        //  基本信息
        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
        goods.setId(skuInfo.getId());
        goods.setDefaultImg(skuInfo.getSkuDefaultImg());
        goods.setPrice(skuInfo.getPrice().doubleValue());
        goods.setTitle(skuInfo.getSkuName());
        goods.setCreateTime(new Date());
        // 分类信息
        BaseCategoryView categoryView = productFeignClient.getBaseCategoryView(skuInfo.getCategory3Id());
        if (categoryView!=null){
            goods.setCategory1Id(categoryView.getCategory1Id());
            goods.setCategory2Id(categoryView.getCategory2Id());
            goods.setCategory3Id(categoryView.getCategory3Id());
            goods.setCategory1Name(categoryView.getCategory1Name());
            goods.setCategory2Name(categoryView.getCategory2Name());
            goods.setCategory3Name(categoryView.getCategory3Name());
        }
        //sku的品牌信息
        BaseTrademark trademark = productFeignClient.getTrademark(skuInfo.getTmId());
        if (trademark!=null){
            goods.setTmId(trademark.getId());
            goods.setTmLogoUrl(trademark.getLogoUrl());
            goods.setTmName(trademark.getTmName());
        }
        //平台属性信息
        List<BaseAttrInfo> baseAttrInfoList = productFeignClient.getAttrList(skuId);
        if (baseAttrInfoList !=null && baseAttrInfoList.size()>0){
            List<SearchAttr> list = baseAttrInfoList.stream().map(baseAttrInfo -> {
                SearchAttr searchAttr = new SearchAttr();
                searchAttr.setAttrId(baseAttrInfo.getId());
                searchAttr.setAttrName(baseAttrInfo.getAttrName());

                //获取属性值的集合
                List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
                searchAttr.setAttrValue(attrValueList.get(0).getValueName());
                //返回对象
                return searchAttr;
            }).collect(Collectors.toList());
            //给goods设置对象
            goods.setAttrs(list);
        }
        //es操作
        goodsRepository.save(goods);
    }

    @Override
    public void lowerGoods(Long skuId) {
        //删掉完成
        goodsRepository.deleteById(skuId);
    }
    //更新热度
    @Override
    public void incrHotScore(Long skuId) {
        //定义一个redis中热度的key
        String hotkey = "hotScore";
        //将热度以自增1的方式放入redis
        Double score = redisTemplate.opsForZSet().incrementScore(hotkey, "skuId" + skuId, 1);
        System.out.println("当前商品====>"+skuId);
        System.out.println("当前热度====>"+score);

        //为减少redis访问量，仅热度为10的倍速时更新
        if (score % 10 ==0){
            //根据id获取es中对应文档对象
            Optional<Goods> optional = goodsRepository.findById(skuId);
            Goods goods = optional.get();
            goods.setHotScore(Math.round(score));
            //es对象更新
            goodsRepository.save(goods);
        }
    }

    @Override
    public SearchResponseVo search(SearchParam searchParam) throws IOException {
        System.out.println("条件========>"+searchParam.toString());
        //1.根据搜索条件生成对应dsl语句
        SearchRequest request = this.buildQueryDsl(searchParam);

        //发请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //解析结果
        SearchResponseVo vo = this.parseResponse(response);

        //5.设置分页相关字段值
        vo.setPageNo(searchParam.getPageNo());
        vo.setPageSize(searchParam.getPageSize());
        long totalPages = (vo.getTotal()+searchParam.getPageSize()-1)/searchParam.getPageSize();
        vo.setTotalPages(totalPages);
        return vo;
    }
    //制作dsl语句的方法
    private SearchRequest buildQueryDsl(SearchParam searchParam){
        //创建一个整体的搜索对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //创建布尔查询
        BoolQueryBuilder boolQueryBuilder =QueryBuilders.boolQuery();
        //根据id查
        if (searchParam.getCategory1Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id",searchParam.getCategory1Id()));
        }
        if (searchParam.getCategory2Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id",searchParam.getCategory2Id()));
        }
        if (searchParam.getCategory3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id",searchParam.getCategory3Id()));
        }
        //根据关键字搜索
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("title",searchParam.getKeyword()).operator(Operator.AND));
        }
        //根据品牌过滤
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)){
            //切割字符串
            String[] split = trademark.split(":");
            if (split!=null && split.length==2){
                boolQueryBuilder.filter(QueryBuilders.termQuery("tmId",split[0]));
            }
        }
        //根据平台属性值过滤
        String[] props = searchParam.getProps();
        if (props!=null && props.length>0){
            for (String prop:props){
                //切割字符串 23:4g 运行内存 属性id:属性值名称：属性名称
                String[] split =prop.split(":");
                if (split!=null && split.length==3) {
                    //创建2个bool查询对象
                    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                    BoolQueryBuilder subBoolQuery = QueryBuilders.boolQuery();
                    //给子查询对象设置平台属性id 属性值名称
                    subBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", split[0]));
                    subBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue", split[1]));
                    boolQuery.must(QueryBuilders.nestedQuery("attrs", subBoolQuery, ScoreMode.None));
                    boolQueryBuilder.filter(boolQuery);
                }
            }
        }
        //将bool查询器设置给整体的搜索对象
        searchSourceBuilder.query(boolQueryBuilder);
        //分页处理
        Integer pageNo = searchParam.getPageNo();
        Integer pageSize = searchParam.getPageSize();
        int from=(pageNo-1)*pageSize;
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(pageSize);
        //排序处理
        String order =searchParam.getOrder();
        if (!StringUtils.isEmpty(order)){
            //切割字符串 1或者2: asc或者desc 1=hotScore 2=price asc=升序 desc=降序
            String[] split =order.split(":");
            String field = "";
            if (split!=null && split.length==2){
                switch (split[0]){
                    case "1":
                        field="hotScore";
                        break;
                    case "2":
                        field="price";
                        break;
                }
                //排序
                SortOrder sortOrder="asc".equals(split[1])? SortOrder.ASC: SortOrder.DESC;
                searchSourceBuilder.sort(field,sortOrder);
            }
        }else {
            //没有排序规则，则默认的按照热度 降序
            searchSourceBuilder.sort("hotScore",SortOrder.DESC);
        }
        //高亮处理
        //编写高亮
        HighlightBuilder  highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style=color:red>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);


        //品牌聚合
        TermsAggregationBuilder tmAgg = AggregationBuilders.terms("tmIdAgg").field("tmId")
                .subAggregation(AggregationBuilders.terms("tmNameAgg").field("tmName"))
                .subAggregation(AggregationBuilders.terms("tmLogoUrlAgg").field("tmLogoUrl"));
        searchSourceBuilder.aggregation(tmAgg);

        //平台属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attrAgg", "attrs")
                .subAggregation(AggregationBuilders.terms("attrIdAgg").field("attrs.attrId")
                        .subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"))
                        .subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"))
                );

        searchSourceBuilder.aggregation(attrAgg);

        //设置只返回部分字段
        searchSourceBuilder.fetchSource(new String[]{"id","title","price","defaultImg"},null);
        //创建请求对象
        SearchRequest request = new SearchRequest("goods");

        //给请求方法
        request.source(searchSourceBuilder);

        System.out.println("生成的dsl语句========>"+searchSourceBuilder.toString());

        return request;
    }
    //制作结果的方法
    private SearchResponseVo parseResponse(SearchResponse searchResponse){
        //创建最终返回的结果对象
        SearchResponseVo vo= new SearchResponseVo();
        //获取


        //----------------获取聚合的对象,获取聚合结果的整体对象 转为Map集合(装载了品牌和平台属性的结果)
        Map<String, Aggregation> aggregationMap = searchResponse.getAggregations().asMap();
        //获取品牌聚合数据对象
        ParsedLongTerms tmIdAgg= (ParsedLongTerms) aggregationMap.get("tmIdAgg");
        List<SearchResponseTmVo> tmVoList = tmIdAgg.getBuckets().stream().map((bucket -> {
            SearchResponseTmVo tmVo = new SearchResponseTmVo();
            //设置id
            String key = ((Terms.Bucket) bucket).getKeyAsString();
            tmVo.setTmId(Long.parseLong(key));
            //设置品牌名字
            ParsedStringTerms tmNameAgg = ((Terms.Bucket) bucket).getAggregations().get("tmNameAgg");
            String tmName = tmNameAgg.getBuckets().get(0).getKeyAsString();
            tmVo.setTmName(tmName);
            //设置品牌的Logo
            ParsedStringTerms tmLoGoUrlAgg = ((Terms.Bucket) bucket).getAggregations().get("tmLogoUrlAgg");
            String tmLoGoUrl = tmLoGoUrlAgg.getBuckets().get(0).getKeyAsString();
            tmVo.setTmLogoUrl(tmLoGoUrl);
            //返回
            return tmVo;
        })).collect(Collectors.toList());
        vo.setTrademarkList(tmVoList);

        //返回平台属性聚合对象
        ParsedNested attrAgg = (ParsedNested) aggregationMap.get("attrAgg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");
        List<SearchResponseAttrVo> attrVoList = attrIdAgg.getBuckets().stream().map((bucket -> {
            //创建平台属性结果vo对象
            SearchResponseAttrVo attrVo = new SearchResponseAttrVo();

            Number attrId = ((Terms.Bucket) bucket).getKeyAsNumber();
            attrVo.setAttrId(attrId.longValue());
            //设置属性名
            ParsedStringTerms attrNameAgg = ((Terms.Bucket) bucket).getAggregations().get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            //属性值聚合获取
            ParsedStringTerms attrValueAgg = ((Terms.Bucket) bucket).getAggregations().get("attrValueAgg");
            List<String> valueList = attrValueAgg.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());

            attrVo.setAttrValueList(valueList);

            return attrVo;
        })).collect(Collectors.toList());
        vo.setAttrsList(attrVoList);
        //获取搜索的商品集合
        SearchHit[] hits =searchResponse.getHits().getHits();
        //创建返回的商品对象
        List<Goods> goodsList = new ArrayList<>();
        if (hits != null && hits.length>0){
            for (SearchHit hit :hits){
                String source = hit.getSourceAsString();
                Goods goods = JSON.parseObject(source, Goods.class);
                if (hit.getHighlightFields().get("title")!=null){
                    //判断是否有高亮显示数据
                        String title = hit.getHighlightFields().get("title").getFragments()[0].toString();
                        goods.setTitle(title);
                }
                goodsList.add(goods);
            }
        }
        vo.setGoodsList(goodsList);
        //设置总数
        vo.setTotal(searchResponse.getHits().totalHits);
        return vo;

    }
}
